package com.levi.mall.controller;

import com.levi.constants.MallConstants;
import com.levi.form.UserLoginForm;
import com.levi.form.UserRegisterForm;
import com.levi.mall.service.UserService;
import com.levi.pojo.User;
import com.levi.vo.ResponseVo;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpSession;
import javax.validation.Valid;

/**
 * @author shentong
 * @since 2022/3/22 9:28 PM
 */
@Api(tags = "用户接口")
@RestController
@RequestMapping("/user")
@Slf4j
public class UserController extends BaseController{
    @Autowired
    private UserService userService;

    @ApiOperation("用户注册")
    @PostMapping("/register")
    public ResponseVo<User> register(@ApiParam("用户注册对象") @Valid @RequestBody UserRegisterForm userRegisterForm) {
        User user = new User();
        BeanUtils.copyProperties(userRegisterForm, user);
        return userService.register(user);
    }

    @PostMapping("/login")
    @ApiOperation("用户登录")
    public ResponseVo<User> login(@ApiParam("用户登录对象") @Valid @RequestBody UserLoginForm userLoginForm,
                                  HttpSession session) {
        ResponseVo<User> responseVo = userService.login(userLoginForm);
        session.setAttribute(MallConstants.CURRENT_USER,responseVo.getData());
        log.info("login  sessionid =>>{}",session.getId());
        return responseVo;
    }

    @PostMapping
    @ApiOperation("获取当前登录用户的信息")
    public ResponseVo<User> userInfo(HttpSession session) {
        User user = getCurrentUser(session);
        log.info("user  sessionid =>>{}",session.getId());
        return ResponseVo.success(user);
    }

    @PostMapping("/logout")
    @ApiOperation("退出登录")
    public ResponseVo<User> logout(HttpSession session) {
        session.removeAttribute(MallConstants.CURRENT_USER);
        return ResponseVo.success();
    }

}
